

if(typeof com == 'undefined') com = {};


if(typeof com.lolita == 'undefined') com.lolita = {};

if(typeof com.lolita.classes == 'undefined') com.lolita.classes = {
   loliAccordionAutoResize      : 'loli-auto-resize'
  ,loliAccordion                : 'loli-accordion'
  ,loliAccordionLoading         : 'loli-accordion-loading'
  ,loliMemberPickLoading        : 'loli-ac-member-loading'
  ,loliMemberPick               : 'loli-ac-member'
  ,loliMemberPickLinked         : 'loli-ac-member-linked'
  ,loliTeamPickLoading          : 'loli-ac-team-loading'
  ,loliTeamPick                 : 'loli-ac-team'
  ,loliTeamPickLinked           : 'loli-ac-team-linked'
  ,loliDuppliBtnGrpWrapper      : 'loli-duppli-btn-grp-wrapper'
  ,loliDuppliBtnGrpRoot         : 'loli-duppli-btn-grp-root'
  ,loliDuppliBtnGrpRootParent   : 'loli-duppli-btn-grp-root-parent'
  ,loliAjaxReport               : 'ajax-report'
  ,loliAjaxReportSuccess        : 'success'
  ,loliAjaxReportError          : 'error'
  ,loliAjaxDynForm              : 'loli-dyn-form'
  ,loliFormCancelButton         : 'dyn-form-loli-cancel-button'
}

if(typeof com.lolita.get == 'undefined') com.lolita.get = {
   ajaxUrl : function(){
    return 'ajax2.php'; 
   }
   ,dynUrl  : function(){
     return 'dyn.php';
   }
   ,themeName : function(){
     var className = document.body.className;
     
     className = className.split("theme-");
     if(className.length>1){
       className = className[1].split(" ");
       className = className[0];
     } else {
       className = "blue";
     }
     return className;
   }
   ,data : function(pars,callback){
     var def = {
          'url' : com.lolita.get.ajaxUrl()
         ,'callback' : callback
         ,'data' : []
         ,'success' :  function(data, textStatus, XMLHttpRequest){
           if(p.callback!=null && jQuery.isFunction(p.callback)){
             p.callback.call(this,data,textStatus,XMLHttpRequest);
           }
         }
         ,'error' : function(XMLHttpRequest, textStatus, errorThrown){
           
         }
     }
     
     var p = jQuery.extend(true,def,pars);
     
     jQuery.ajax(p);
  }
  ,teamByYear : function (year,callback){
    com.lolita.get.data({
      data : {
         'action' : 'get'
        ,'what'   : 'equipe'
        ,'sub'    : 'yearList'
        ,'more'   : {
          'year'  : year
        }
      }
      ,'dataType' : 'json'
    },callback);
  }
  ,ajaxUrlArray : function (url){
    if(url==null){
      url = window.location;
    }
    ret   = {};
    pars  = url.split('#!/');
    sep   = '/';
    
    if(pars.length<=1){
      pars = url.split('?');
      sep='&';
    }
    
    if(pars.length>1){
      pars  = pars[1].split(sep);
      var j = pars.length;
      for(var i=0;i<j;++i){
        switch(sep){
        case '/':
          if(i+1<j){
            ret[pars[i]]=pars[i+1];
            i++;
          } else {
            ret[pars[i]]=null;
          }
          break;
        case '&':
          var tmp = pars[i].split('=');
          if(tmp.length==1){
           ret[tmp[0]]=null;
          }
          ret[tmp[0]]=tmp[1];
          break;
        }
      }
      
    }
    return ret;
  }
}

if(typeof com.lolita.get.match == 'undefined') com.lolita.get.match = {};
com.lolita.get.match  = function (){
  
}

  
if(typeof com.lolita.get.match.pics == 'undefined') com.lolita.get.match.pics = {};
com.lolita.get.match.pics  = function (id){
  com.lolita.get.data({
      data : {
         'action' : 'get'
        ,'what'   : 'images'
        ,'sub'    : 'match'
        ,'more'   : {
          'id'  : id
        }
      }
      ,'dataType' : 'json'
    }, function(rep){
      if(rep.status==true){
        
        jQuery('#fancybox-thumbs img').error(function(){
          console.log('error',this.src);
        });
        
        jQuery.fancybox.close();
        var i=0;
        var exist=false;
        jQuery.fancybox.open(rep.success.datas.images,{
          closeBtn		: false
         ,helpers		: {
             title	: { type : 'inside' }
            ,buttons	: {}
            ,thumbs	: {
               width   : 50
              ,height  : 50
              ,source : function(item){
                
                var path  = item.href.split(/[\\\/]/);
                var name  = path.pop();
                var url   = path.join('/')+'/miniature/'+name; //com.lolita.get.dynUrl()+'?a=g&w=min&s=m&id='+id+'&name='+name; 
                if(++i==1){
                  jQuery.ajax({
                    url: url
                    ,success: function(){ exist=true }
                    ,error: function(){ exist=false }
                    ,async: false
                  });
                } 

                if(!exist){
                  url   = com.lolita.get.dynUrl()+'?a=g&w=min&s=m&id='+id+'&name='+name;
                }

                return url;
              }
           }
         }
        ,beforeShow: function () {
            /* Add watermark */
            jQuery('<div class="credits"><div>'+rep.success.datas.credits.join(' / ')+'</div></div>')
                .bind("contextmenu", function (e) {
                    return false; /* Disables right click */
                })
                .prependTo( jQuery.fancybox.inner );   
                
            
                
          } 
        });
        
      }
  });
  
}

if(typeof com.lolita.utils == 'undefined') com.lolita.utils = {

  updateImagesCount : function(saisonId,callback){
    
    if(callback==null) callback = jQuery.noop();
    
    com.lolita.get.data({
      data : {
         'action' : 'update'
        ,'what'   : 'image-count'
        ,'id'     : saisonId
      }
      ,'dataType' : 'json'
    },callback);
  }

  ,addHeadLink  : function (params){
    if(!jQuery.isPlainObject(params)){
      params = {"href" : params};
    }

    //<link rel="stylesheet" media="screen" type="text/css" href="" />
    var $ret = jQuery('<link />',params);
    
    if(params.removeOnError){
      $ret.error(function(){
        jQuery(this).remove();
      });
    }
    
    $ret.prependTo(jQuery('head'))
    
    return $ret;
  }
  
  ,serializeFormObject : function(form){
    
    var obj = {};
    
    var tmp = jQuery(form).serializeArray();
    
    jQuery.each(tmp,function(idx,prop){
      obj[prop.name] = prop.value;
    })
    
    return obj;
  }

  ,cancelEvent : function (event){
    event.stopPropagation();
    event.cancelBubble = true;
    return false;
    
  }
  
  ,doStyleSheet : function(params,mode){

    if(!jQuery.isPlainObject(params)){
      params = {"href" : params};
    }

    var $ret, p , def = {
       "href" : ''
      ,"rel" : "stylesheet"
      ,"media" : "screen"
      ,"type" : "text/css"
      ,"removeOnError" : true
    }
    p     = jQuery.extend(true,{},def,params);
    $ret  = jQuery('link[href="'+p.href+'"]');

    var cnt = 0;

    if($ret.length==0 || $ret.attr('media')!=p.media || $ret.attr('rel')!=p.rel || $ret.attr('type')!=p.type){
      if(mode!='rem'){
        $ret = com.lolita.utils.addHeadLink(p);
      }
    } else {
      cnt = $ret.data('add-cnt');
      if(isNaN(cnt))  cnt = 0;
      if(mode=='rem'){
        if(cnt==1){
          // On ne vire pas on désactive
          $ret.attr('disabled',true);
        } 
        
        $ret.data('add-cnt',cnt-1);

      } else {
        // On réactive
        $ret.attr('disabled',false);
      }
    }

    if(mode!='rem'){
      $ret.data('add-cnt',cnt+1);
    }

    return $ret;
  }

  ,doWidgetStyleSheet  : function (widgetName,mode){
    
    if(widgetName.match(/\.css$/)==null) widgetName=widgetName+'.css';

    if(mode==null || mode==''){ mode='rem'; }
    var theme = com.lolita.get.themeName();
    css = 'css/widgets/'+widgetName;
    var cnt=0;
    cnt+=com.lolita.utils.doStyleSheet(css,mode);
    css = 'css/themes/'+theme+'/widgets/'+widgetName;
    cnt+=com.lolita.utils.doStyleSheet(css,mode);
    return cnt;
  }

  ,addWidgetStyleSheet  : function (widgetName){
    return com.lolita.utils.doWidgetStyleSheet(widgetName, 'add');
  }
  
  ,remWidgetStyleSheet  : function (widgetName){
    return com.lolita.utils.doWidgetStyleSheet(widgetName, 'rem');
  }
  
  ,addStyleSheet  : function (params){
    return com.lolita.utils.doStyleSheet(params, 'add');
  }

  ,remStyleSheet  : function (params){
    return com.lolita.utils.doStyleSheet(params, 'rem');
  }
  
  ,addScript   : function (params,test){
    if(!jQuery.isPlainObject(params)){
      params = {"src" : params};
    }
    
    if (typeof com.lolita.addedScript == 'undefined') com.lolita.addedScript = [];
    
    if(test==null)  test = false;

    var $ret, p , def = {
        "src"  : ""
       ,"type" : "text/javascript"
       ,"data-generator" : "com.lolita"
    }
    p = jQuery.extend(true,{},def,params);

    if(com.lolita.addedScript.indexOf(p.src)==-1){
      $ret = jQuery('<script />',p).attr('src',p.src);
      $ret.prependTo(jQuery('head'));
      com.lolita.addedScript.push(p.src);
    } else {
      // déjà dedans on fait rien de special
      com.lolita.addedScript;
    }
    return $ret;
  }
  
  ,addWidgetScript  : function (widgetName){
    var theme = com.lolita.get.themeName();
    var js = 'js/widgets/'+widgetName;
    var cnt=0;
    cnt+=com.lolita.utils.addScript(js,false);
    js = 'js/themes/'+theme+'/widgets/'+widgetName;
    cnt+=com.lolita.utils.addScript(js,false);
    return cnt;
  }
  
  ,isValidMail  : function(mail){
    var re = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/gi;
    return re.test(mail);
}

};

if (typeof com.lolita.redoJsonBrOnTextarea == 'undefined') com.lolita.redoJsonBrOnTextarea = {};
com.lolita.redoJsonBrOnTextarea = function (selector){
  if(selector==null){
    selector = "textarea:contains(¤)";
  }
  jQuery(selector).each(function(){
    var $this = jQuery(this);
    var text = $this.val();
    text = text.replace(/¤/gi,'\n');
    $this.val(text);
  })
}

if(typeof com.lolita.makeColorPicker == 'undefined') com.lolita.makeColorPicker = {};
com.lolita.makeColorPicker  = function (selector,params){

  try{
      com.lolita.utils.addStyleSheet('js/colorpicker/css/colorpicker.css');
      com.lolita.utils.addScript('js/colorpicker/js/colorpicker.js',(jQuery.fn.ColorPicker==null));

     var p = jQuery.extend(true,{},{"zIndex" :"1300",onInit:jQuery.noop},params);
     var $colorInput = jQuery(selector);
     $colorInput.addClass('color-picker');
     $colorInput.ColorPicker({
         "eventName" : "click"
        ,"color" : $colorInput.val()
        ,onSubmit: function(hsb, hex, rgb, el) {
          $colorInput.val('#'+hex);
          $colorInput.css('background-color','#'+hex);
          $colorInput.ColorPickerHide();
        }
        ,onBeforeShow: function () {
          jQuery('.colorpicker').css('z-index',p.zIndex);
        }
        ,onChange: function (hsb, hex, rgb) {
          $colorInput.css('backgroundColor', '#' + hex);
        }
        ,onHide: function(el){
          var hex = $colorInput.val();
          $colorInput.css('background-color',hex);
        }
     });

     if($colorInput.ColorPicker && p.onInit.apply($colorInput.get(0),p)!=false ){
       
     }

/*     $colorInput.hide(0,function(){
      var $this = jQuery(this);

      var $pickColor = jQuery('<div class="color-picker"><div style="background-color: '+$this.val()+'"></div></div>');
      $pickColor.insertBefore($this)
      $pickColor.wrap('<span style="position: relative"/>');

      $pickColor.ColorPicker({
         "eventName" : "click"
        ,"color" : $this.val()
        ,onSubmit: function(hsb, hex, rgb, el) {
          $this.val('#'+hex);
          $pickColor.children().css('background-color','#'+hex);
          $pickColor.ColorPickerHide();
        }
        ,onBeforeShow: function () {
          jQuery('.colorpicker').css('z-index',p.zIndex);
        }
        ,onChange: function (hsb, hex, rgb) {
          jQuery('div',$pickColor).css('backgroundColor', '#' + hex);
          if (console) console.log(this);
        }
      });
  
    });
*/
  } catch(e){
    if(console) console.log(e);
  }
}

if(typeof com.lolita.display == 'undefined') com.lolita.display = {

  blinkItem : function (item,params){
    
    var p={};
    
    p = jQuery.extend({},params,{
       'delai'    : 200
      ,'loop'     : 9
    });    
        
    if(typeof item == "string"){
      item = jQuery(item);
    } else if (typeof item == "object" && typeof item.fn == "undefined"){
      item = jQuery(item);
    }
      
    var blink = function(){
      //item.stop(false,true);
      if(--p.loop>0){
        if(p.loop % 2 != 0){
          item.fadeOut(p.delai,function(){blink();});
        } else {
          item.fadeIn(p.delai,function(){blink();});
        }
      } else {
        item.fadeIn(p.delai);
      }
    };
    
    blink();
    
  
  }
  
  ,setLoliDialogTitle : function(title,parent){
    var $parent = jQuery(parent || '.ui-dialog');
    var $title  = jQuery(title  || '.loli-dialog-title',$parent);

    jQuery('.ui-dialog-title',$parent).html($title.hide().html());
  }
  
  ,showLoginDialog : function(){
   
   
   
  }
  
 ,makeLoliTab : function(selector,pars){
    var $el = jQuery(selector || '.loli-tab');
    if(!pars) pars = {};

     var d = {
       "selected":0
      ,"heightStyle" : "fill"
      ,"show": function(event, ui) {
        if(ui.panel){
          var $acc = jQuery(ui.panel).find('.'+com.lolita.classes.loliAccordion);
          if($acc.length>0){
            if($acc.is('.'+com.lolita.classes.loliAccordionAutoResize)){
              $acc.accordion( "resize" );
            }
          }
        }
      }
    }

    var p = jQuery.extend({},d,pars);

    $el.tabs(p).addClass(com.lolita.classes.loliTab);

    return $el;
  }

  ,makeCancelButton :  function (selector){
    var $el = jQuery(selector || 'button.btn-annuler-saisie');
    $el.button({
      icons : {primary : 'ui-icon-arrowrefresh-1-s'}
    })

    return $el;
  }

  ,makeDynFormCancelButton : function(selector){
    var $btn = com.lolita.display.makeCancelButton(selector);

    $btn.each(function(){

      var $this = jQuery(this);
      if($this.is('.'+com.lolita.classes.loliFormCancelButton))  return;
      $this.addClass(com.lolita.classes.loliFormCancelButton);

      $this.bind('click.dyn-form-loli-cancel-button',function(event){
        if(event.which != 1){
          return true;
        }
        var $form,$this = jQuery(this);
        event.preventDefault();
        $form = $this.closest('form');
        if($form.length>0){
          var $input = jQuery('<input />',{
             "name"   : "action"
            ,"value"  : "get"
            ,"type"   : "hidden"
          });
          $form.append($input).submit();
        }

        return false;

      });
    });
    return $btn;
  }

  ,addDynForm : function(selector,params){

    com.lolita.utils.addScript('js/jquery.form.js',(jQuery.fn.ajaxSubmit==null));
      
    
    var $el = jQuery(selector || '.'+com.lolita.classes.loliAjaxDynForm);

    if(!jQuery.isPlainObject(params)){
      params = {"what" : params};
    }

    var p,def = {
      'action'      : 'update'
      ,'addReport'  : true
      ,'callback'   : {
         'success'   : jQuery.noop
        ,'beforeSubmit'   : jQuery.noop
      }
    }

    p = jQuery.extend(true,{},def,params);

    var wrapContent = function($this){
      $this.contents().wrapAll('<div />');
    }

    $el.each(function(idx,el){

      el = jQuery(el);

      var $form = null;

      if(el.is('form')){
        $form =el;
      } else {
        $form = el.find('form');
      }

      if(!$form)  return;
      
      if(p.addReport==true && jQuery('.'+com.lolita.classes.loliAjaxReport,$form).length==0){
        jQuery('<div class="'+com.lolita.classes.loliAjaxReport+'"></div>').hide().prependTo($form);
      }

      $form.submit(function(e){
        e.preventDefault();
        var $this = jQuery(this);
        wrapContent($this);
        var $action = $this.find('[name="action"]');
        // On repart a chaque fois de p
        var data = jQuery.extend({},p);
        // et on intervient sur data au besoin
        if($action.length>0 && $action.val()!=''){
          data.action = $action.val();
        }
        
        var dataType = "json";

        $this.ajaxSubmit({
           "data" : data // on utilise data et non p
          ,"type" : "POST"
          ,"dataType" : dataType
          ,"beforeSend" : function(){
            $this.parent().scrollTop(0);
            com.lolita.display.addAjaxLoading($this);
            $this.find('div:last-child').hide();
          }
          ,"beforeSubmit" : p.callback.beforeSubmit
          ,"success" :  function(data,textStatus,xhr,$form){
            if(!data)
              return false;

            if(data.more)
              $this.html(data.more);

            wrapContent($this);

            if(data.success){
              com.lolita.display.addReport(data.success, '.'+com.lolita.classes.loliAjaxReportSuccess, '.'+com.lolita.classes.loliAjaxReport, $this);
            }

            if(data.errors){
              com.lolita.display.addReport(data.errors, '.'+com.lolita.classes.loliAjaxReportError, '.'+com.lolita.classes.loliAjaxReport, $this);
            }
            
            if(data.success || data.errors){
              //com.lolita.display.addReport(data.errors, '.'+com.lolita.classes.loliAjaxReportError, '.'+com.lolita.classes.loliAjaxReport, $this);
            }

            if(p.callback.success && jQuery.isFunction(p.callback.success)){
              p.callback.success.call(data,textStatus,xhr,$form);
            }
            
          }
        }).addClass(com.lolita.classes.loliAjaxDynForm);
        return false;
      });

    })
    
    com.lolita.display.makeDynFormCancelButton();
  }
  ,addReport : function(data,className,appendTo,parent){
      var $ret = null;
      if(jQuery.isArray(data) && data.length>0){
        $ret = jQuery(appendTo,parent).html(jQuery('<ul></ul>').addClass(className).html(jQuery(data).map(function(){
            return '<li>'+this+'</li>';
          }).get().join(''))).fadeOut(0).fadeIn(1000);
      }
      return $ret;
  }
  ,addAjaxLoading : function(selector,params){
    
    var $parent =  jQuery(selector);
    var $loader,p,def = {
        "template" : com.lolita.display.get.loaderTemplate({"img":"big-loading.gif","text":"Chargement en cours"})
      , "fullsize" : true
    };
    p = jQuery.extend({},def,params);

    $loader = jQuery(p.template);

    if(p.fullsize){
      var dim = {
        "width" : $parent.width()
        ,"height" : $parent.height()}
      $loader.css(dim);
    }

    $parent.prepend($loader);
    return $loader;
  }
  
  ,callAjaxItem : function(pars,callBack){
    jQuery.get(com.lolita.get.dynUrl(),pars,function(data,txtSt,xhr){
      var $data   = jQuery(data);
      var datas   = $data.find('item').map(function(){
        var item  = {}
        for(i=0;i<this.attributes.length;i++){
          var attr=this.attributes[i];
          item[attr.nodeName] = attr.nodeValue;
        }
        
        if((typeof item.value == 'undefined' || item.value==0) && item.id){
          item.value = item.id;
        }
        
        return item;
      }).get();
      
      if(jQuery.isFunction(callBack)){
        callBack(datas);
      }
      
    },'xml');

  }

  ,makeAutoComplete : function (selector,parent,pars){
        
//        return false;

      var returnData = function (datas,pars,term){
        var ret = null;
        
        ret = pars.acOptions.filter(datas, term);
        
        if((ret == null ) && p.onEmpty!=null){
          ret = p.onEmpty;
        }
        
        if(term.charAt(0)=='^' && ret.length==1){
          $this.data("autocomplete")._trigger("select",null,{item : ret});
        }
        
        return ret;
      }
        
      var $ac,p,p1,def = {
         "onEmpty" : {"id" : 0, "label" : '', "overwriteValue" :0}
        ,"storeData"  : true
        ,"getPars"    : null
        ,"getSource"  : null
        ,"getSourceKey" : null
        ,"callback"     : {
          
        }
        ,"cpl"        : {}
        // Options de l'autocomplete'
        ,"acOptions"  : {
           "classLoading" : com.lolita.classes.loliAccordionLoading
          ,"minLength"  : 2
          ,"pars"       : {
             "a"  : null
            ,"w"  : null
            ,"m"  : {
               "sub"          : "list-xml"
              ,"displayType"  : true
              ,"typeFilter"   : "*"
            }
          }
          ,"filter" : function(array,term){
              
              var matcher = new RegExp(jQuery.ui.autocomplete.escapeRegex(term), "i" );
              return jQuery.grep( array, function(value) {
                var ret = false;
                
                var test = '';
                
                test = (value.pickLabel ?  value.pickLabel : value.label);
                  
                ret = matcher.test(test);// ||  matcher.test(value.value)  ||  matcher.test(value.id);
                return ret;
              });
              
          }          
          ,"search" : function(){
            jQuery(this).addClass(com.lolita.classes.loliTeamPickLoading);
          }
          ,"source"     : function(request,response){
            var $ac = jQuery(this.element);
            var key = null;
            
            if(jQuery.isFunction(p.getPars)){
              p = jQuery.extend(true,{},p,p.getPars.call($ac,p));
            }            

            if(p.storeData && jQuery.isFunction(p.getSourceKey)){
              key = p.getSourceKey.call($ac.get(0),request,response,p);
            } 
            
            if(p.storeData){
              var datas = $ac.data('loli-autocomplete-data['+key+']');
              if(datas){
                return response(returnData(datas,p,request.term));
              }
            }
            
            if(jQuery.isFunction(p.getSource)){
              p.getSource.call($ac.get(0),request,response,p);
            } else {   
              var pars = jQuery.extend(true,{},p.acOptions.pars,{'request' : request});
              com.lolita.display.callAjaxItem(pars, function(datas){
                
                if(p.storeData){
                  $ac.data('loli-autocomplete-data['+key+']',datas);
                }
                
                var startSearch = $ac.autocomplete( "option", "_startSearch");
                
                var retData = returnData(datas,p,request.term);
                
                if(retData.length==0){
                  retData = datas;
                }
                
                var selected = null;
                
                if(startSearch){
                  $ac.autocomplete( "option", "_startSearch",false);
                  var matcher = new RegExp('^'+jQuery.ui.autocomplete.escapeRegex(request.term)+'$', "i" );
                  selected = jQuery.grep(retData, function(value) {
                    var ret = false;
                    ret = matcher.test(value.id);
                    return ret;
                  });

                  if((selected==null || selected.length==null || selected.length==0) && p.onEmpty){
                    if(typeof p.onEmpty != 'string' || p.onEmpty.toUpperCase() !='SELF'){
                      selected = [p.onEmpty];
                    } else {
                      // on simule une réponse "SELF"
                      selected = ['SELF'];
                    }
                  }
                  if((selected.length!=null && selected.length==1)){
                    $ac.data("autocomplete")._trigger("select",null,{item : selected[0]});
                  }
                  
                } else {
                  response(retData);
                }                
              });
            }
          }
          ,"open" : function(event,ui){
            var $this = jQuery(this);
            if($this.is('.ac-open-up')){
              var $menu = $this.autocomplete("widget");
              var top =parseInt($menu.css('top')) - $menu.outerHeight(true) - $this.outerHeight(true);
              $menu.css({
                "top" : top
              });
            }
          }
          ,"select" : function(event,ui){
              var $this = jQuery(this);
              
              if(typeof ui.item == "string" && ui.item.toUpperCase()=="SELF"){
                // On ne fait rien on laisse la valeur par défaut de l'item
              } else {

                if(typeof ui.item.pickLabel !== 'undefined' && ui.item.pickLabel!=''){
                  $this.val(ui.item.pickLabel);
                } else {
                  $this.val(ui.item.label);  
                }

                var $linked = $this.data('linked');
                $linked.val(ui.item.id);
                $linked.data('rel-item',ui.item);
              
              }
              
              if(p.callback && p.callback.onSelect && jQuery.isFunction(p.callback.onSelect)){
                p.callback.onSelect.call($this.get(0),ui);
              }
            return false;
          }
          ,"focus" : function(event,ui){
            var $this = jQuery(this);
            if(typeof ui.item.pickLabel !== 'undefined' && ui.item.pickLabel!=''){
              $this.val(ui.item.pickLabel);
            } else {
              $this.val(ui.item.label);  
            }
            return false
          }
          ,"create" : function(){
            
            var self  = this;
            var $self = jQuery(self);
            
            $self.autocomplete( "option", "_startSearch", false); 
            var name = $self.attr('name');
            $self.attr('name','ac-'+name);
            $self.addClass(com.lolita.classes.loliTeamPick+' '+com.lolita.classes.loliTeamPickLoading);

            var $new = $self.prev(':eq(0)');

            if($new.length==0 || !$new.is('.'+com.lolita.classes.loliTeamPickLinked)){
              $new = jQuery('<input/>').attr({
                'type':'hidden'
                ,'name' : name
                ,'class' : com.lolita.classes.loliTeamPickLinked
                ,'value' : $self.val()
              }).insertAfter($self);
            }

            $self.data('linked',$new);

            // Onfocus on doit annuler la valeur du hidden
            // car on peux rechercher qq chose de completement différent
            // en même finir avec qq d'inconnu
            $self.keyup(function(event){
              var $this   = jQuery(this);
              var $linked = $this.data('linked');
              var item    = $linked.data('rel-item');
              if(item){
                if($this.val()!=item.label && $this.val()!=item.pickLabel){
                  $linked.val(0);
                } else {
                  $linked.val(item.id);
                }
              }
            }).keydown(function(event){
              var $this   = jQuery(this);
              if(event.keyCode == 40){
                if($this.val()==''){
                  $this.data("autocomplete")._trigger("open");
                }
              }
            });
            
            if(p.acOptions && jQuery.isFunction(p.acOptions.renderItem)){
              $self.data("autocomplete")._renderItem = p.acOptions.renderItem;
            }
            
            if($self.val() && $self.val()!=0 && $self.val()!=''){
              // Si on a une valeur de départ on recherche, mais attention, on défini minlength au minimum
              // Si on recherche un id pour une équipe
              var minLength = $self.autocomplete( "option", "minLength" );
              $self.autocomplete( "option", "minLength", 0 );              
              $self.autocomplete( "option", "_startSearch", true );              
              $self.autocomplete("search",$self.val());
              $self.autocomplete( "option", "minLength",minLength);
            } else {
              if(p.onEmpty){
                $self.data("autocomplete")._trigger("select",null,{item : p.onEmpty});
              }
            }
          }
          ,"renderItem" : function( ul, item ) {
              return jQuery( "<li></li>" ).css('white-space','nowrap')
              .data( "item.autocomplete", item )
              .append( jQuery( '<a><img src="'+item.icon+'" class="photo-min"/>'+item.label+'</a>'))
              .appendTo( ul );
          }
        }
      }
      
      p1 = jQuery.extend(true,{},def,pars);
      
      if(!parent) parent = document;
          
      var $el = jQuery(selector,parent);
      
      $el.each(function(){
        $ac = jQuery(this);
        
        if(p1.placeHolder!=""){
          $ac.attr('placeholder',p1.placeHolder);
        }
        
        if(jQuery.isFunction(p1.getPars)){
          p = jQuery.extend(true,{},p1,p1.getPars.call($ac,p1));
        } else {
          p = jQuery.extend({},p1);
        }
        
        $ac.bind('autocompletesearch autocompleteopen autocompleteselect',function(event){
          var $this = jQuery(this);
          if(event.type=='autocompletesearch'){
            $this.addClass(p.acOptions.classLoading);
          } else {
            setTimeout(function(){
              $this.removeClass(p.acOptions.classLoading);
            },250);
          }
        });
        $ac.autocomplete(p.acOptions);
        
      });
    
    return $el;
    
  }
  ,makeMemberPick : function(selector,parent,pars){
    if(!parent) parent  = document;
    var p,p1,def = {
      "acOptions": {
        "pars" : {
           "a"  : "g"
          ,"w"  : "m"
        }
      }
      ,"storeData"    : true
      ,"placeHolder" : "Tapez,attendez,choisissez"
      
    }
    
    p1 = jQuery.extend(true,{},def,pars);

    com.lolita.display.makeAutoComplete(selector, parent, p1);
  }

  ,makeMemberPickBySex : function(sexe,selector,parent,pars){
    if(!parent) parent  = document;
    var p,p1,def = {
      "acOptions": {
        "pars" : {
          "m"  : {
            "sexe" : sexe // 1 =  Homme, 2 =  Femme
          }
        }
      }
    }
    
    p1 = jQuery.extend(true,{},def,pars);

    com.lolita.display.makeMemberPick(selector, parent, p1);
  }
  
  ,makeTeamPick : function(selector,parent,pars){
    if(!parent) parent  = document;
    var p,p1,def = {
      "acOptions": {
        "pars" : {
           "a"  : "g"
          ,"w"  : "e"
        }
      }
      ,"getPars" : function(p){
        var $this     = jQuery(this);
        var saison_id = $this.attr('saison_id');  
        if(saison_id){
          if(!p.more) p.more = {};
          p.more.saison_id = saison_id;
        }
        return p;
      }
      ,"storeData"    : true
      
    }
    
    p1 = jQuery.extend(true,{},def,pars);

    com.lolita.display.makeAutoComplete(selector, parent, p1);
  }
  
  ,makeTeamSaisonPick : function(selector,parent,pars){
    if(!parent) parent  = document;
    var p,p1,def = {
      "acOptions": {
         "pars" : {
           "a"  : "g"
          ,"w"  : "es"
          ,'m'  : {
            "saison_id" : 0
          }
        }
        ,'minLength' : 0
      }
      ,'getPars' : function(p){
        var $this = jQuery(this);
        
        var saison_id = $this.attr('saison_id');
        
        jQuery.extend(true,p,{
          'acOptions' : {
            'pars' : {
              'm': {
                'saison_id': saison_id
              }
            }
          }
        });
        
        return p;
      }
      ,"storeData"    : true
      ,"getSourceKey" : function(request,response,pars){
        var ret = null;
        if(pars.storeData){
          ret = pars.acOptions.pars.m.saison_id;
        }
        return ret;
      }
      
    }
    
    p1 = jQuery.extend(true,{},def,pars);

    com.lolita.display.makeAutoComplete(selector, parent, p1);
  }
  
  ,makeTeamPickWithYear : function(selector,parent,pars){
    if(!parent) parent  = document;
    var p,p1,def = {
      "acOptions": {
        "pars" : {
           "a"  : "g"
          ,"w"  : "esy"
        }
      }
      ,"getPars" : function(p){
        var $this     = jQuery(this);
        var saison_id = $this.attr('saison_id');  
        if(saison_id){
          if(!p.more) p.more = {};
          p.more.saison_id = saison_id;
        }
        return p;
      }
      ,"storeData"    : true
      
    }
    
    p1 = jQuery.extend(true,{},def,pars);

    com.lolita.display.makeAutoComplete(selector, parent, p1);
  }

  ,makeAccordion : function(selector,parent,pars){
    if(!parent) parent  = document;
    if(!pars)   pars    = {}

    var p,d = {
       "heightStyle": "fill"
      ,"autoResize" : true
    }
    p = jQuery.extend({},d,pars);
    var $el = jQuery(selector,parent).accordion(p).addClass(com.lolita.classes.loliAccordion);

    if(p.autoResize){
      $el.addClass(com.lolita.classes.loliAccordionAutoResize);
    }

    return $el;
  }
  ,makeDuppliBtnGrp : function(selector,parent,pars){

    if(jQuery.isPlainObject(selector) && !pars){
      pars      = selector;
      selector  = '';
    }

    selector = selector || '.btn-duppli';

    if(!parent) parent  = document;

    jQuery(selector,parent).each(function(){
    var $el = jQuery(this);

    if($el.data('loli-btngrp-duppli-ok')==true)
        return;
    $el.data('loli-btngrp-duppli-ok',true);

     if(!pars) pars = {};


     var  d = {
         "root"       : $el.attr('loli-dupplibtngrp-root') || "li"
        ,"max"        : $el.attr('loli-dupplibtngrp-max')  || 0
        ,"afterClone" : jQuery.noop
      }

      var p = jQuery.extend({},d,pars)


      if (p.root){
        var $root = $el.closest(p.root);
        $root.addClass(com.lolita.classes.loliDuppliBtnGrpRoot);
        $root.parent().addClass(com.lolita.classes.loliDuppliBtnGrpRootParent)
        var $wraper = jQuery('<span />').addClass(com.lolita.classes.loliDuppliBtnGrpWrapper).appendTo($root.parent()).append($el.find(':button'));
        $wraper.buttonset().find(':button:disabled').removeAttr('disabled').button('disable');

        var appendToLine = function (line){
          var $wraper = jQuery('.'+com.lolita.classes.loliDuppliBtnGrpWrapper,line.parent());
          jQuery(selector,line).append($wraper.show());
          $wraper.find(':button').removeClass('ui-button-disabled ui-state-disabled ui-state-focus ui-state-hover');
        }

        appendToLine($root);

        $root.parent().delegate(p.root,'mouseenter',function(event){
           appendToLine(jQuery(this));
        });
      }

      $wraper.click(function(event){
            $wraper = jQuery(this); 

            var removeRoot = function ($node){
              $node.fadeOut(250,function(){
                $wraper.hide().appendTo($node.parent());
                $node.remove();
              });
            }

            var $target = jQuery(event.target);
            if(event.which != 1)               return true;
            if($target.is(':not(.add,.del)'))  return true;

            event.preventDefault();
            event.stopPropagation();

            var $this   = jQuery(this);

            if (p.root){
              var $root = $this.closest(p.root).addClass(com.lolita.classes.loliDuppliBtnGrpRoot);
              var len   = jQuery('.'+com.lolita.classes.loliDuppliBtnGrpRoot,$root.parent()).length;
              switch(len){
               case 2:
                if($target.is('button.del')){
                  removeRoot($root);
                  len--;
                }
               case 1:
                if($target.is('.del')){
                  jQuery(':input',$this).val(null);
                  jQuery('.del',$wraper).button('disable');
                  appendToLine($root);
                  break;
                }
               default:
                if($target.is('.del')){
                  removeRoot($root);
                  len--;
                } else {
                  if(p.max==0 || len<p.max ){
                    var $clone = $root.clone();
                    $clone.find(selector).children().remove();
                    $clone.hide().insertAfter($root).find(':input',$this).val(null);
                    appendToLine($clone);
                    $clone.fadeIn(800);
                    jQuery('.del,.add',$wraper).button('enable');
                    len++;

                    if(jQuery.isFunction(p.afterClone)){
                      p.afterClone($clone);
                    }
                  }
                }
                if(p.max!=0 && len>=p.max ){
                  jQuery('.add',$wraper).button('disable');
                } else {
                  jQuery('.add',$wraper).button('enable');
                }
                break;
              }
            }
          return false;
        });
      });
  }
}